<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-充值审核 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\common\model;
use think\facade\Db;
use app\api\controller\Index;

class CardsTran extends Common
{
    //---------------------------------------------后端---------------------------------------------------------------
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdmin($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['user_name']) && !empty($post['user_name'])){
            $where[] = ['username', 'like', '%'.$post['user_name'].'%'];
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            $where[] = ['c.card_num', 'like', '%'.$post['card_num'].'%'];
        }
        if(isset($post['app_code']) && !empty($post['app_code'])){
            $where[] = ['c.card_num', '=', $post['app_code']];
        }
        if(isset($post['tran_type']) && !empty($post['tran_type'])){
            $where[] = ['ct.tran_type', '=', $post['tran_type']];
        }
        if(isset($post['tran_token']) && !empty($post['tran_token'])){
            $where[] = ['ct.tran_token', '=', $post['tran_token']];
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00");
            $end_time   = strtotime($time_list[1] . " 23:59:59");
            $where[] = ['ct.ctime', 'between', "{$start_time},{$end_time}"];
        }
        $list = Db::name('cards_tran')->alias('ct')
            ->leftJoin('cards c','c.card_token=ct.card_token')
            ->leftJoin('user u' , 'u.id=ct.user_id')
            ->field('u.username,c.first_name,c.last_name,ct.*')
            ->order('ct.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        $list_data = $list['data'];
        if(isset($list_data) && !empty($list_data)){
            foreach ($list_data as &$v){
                if($v['tran_type'] == "CREDIT"){
                    $v['amount'] = - $v['amount'];
                    $v['amount_real'] = - $v['amount_real'];
                }
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list_data,
            'count' => $list['total'],
        ];
    }

    public function getShops($post)
    {
        $where = "ct.state !='DECLINED' and ct.type in ('authorization.clearing','authorization','refund')";
        if(isset($post['shop_name']) && !empty($post['shop_name'])){
            $shop_name = strtolower($post['shop_name']);
            $where .= " and lower(ct.desc) like '%{$shop_name}%'";
        }
        if(isset($post['user_id']) && !empty($post['user_id'])){
            $where .= " and c.user_id = {$post['user_id']}";
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            $where .=  " and (ct.ctime between {$start_time} and {$end_time})";
        }
        $list = Db::name('cards_transactions')->alias('ct')
            ->join('cards c','c.card_token=ct.card_token')
            ->where($where)
            ->field('sum(ct.amount) amount,ct.desc shop,ct.type')
            ->group('ct.desc,ct.type')
            ->select()->toArray();
        $array_1 = [];
        $array   = [];
        if($list){
            foreach($list as $v){
                if($v['type'] == 'authorization' || $v['type'] == 'authorization.clearing'){
                    if(isset($array_1[$v['shop']])){
                        $array_1[$v['shop']] += $v['amount'];
                    }else{
                        $array_1[$v['shop']] = $v['amount'];
                    }
                }else{
                    if(isset($array_1[$v['shop']])){
                        $array_1[$v['shop']] -= $v['amount'];
                    }else{
                        $array_1[$v['shop']] = -$v['amount'];
                    }
                }
            }
            $google = 0.00;
            $jd_com = 0.00;
            $meituan= 0.00;
            $paypal = 0.00;
            $aliexpress =0.00;
            $apple  = 0.00;
            $pp     = 0.00;
            $facebk = 0.00;

            foreach ($array_1 as $key=>&$value){
                if(strstr(strtolower($key) ,'google')){
                    $google += $value;
                    unset($array_1[$key]);
                }
                if(strstr(strtolower($key),'jd.com')){
                    $jd_com += $value;
                    unset($array_1[$key]);
                }
                if(strstr(strtolower($key) ,'meituan')){
                    $meituan += $value;
                    unset($array_1[$key]);
                }
                if(strstr(strtolower($key) , 'paypal')){
                    $paypal += $value;
                    unset($array_1[$key]);
                }
                if(strstr(strtolower($key) , 'aliexpress')){
                    $aliexpress += $value;
                    unset($array_1[$key]);
                }
                if(strstr(strtolower($key) , 'store.apple.com')){
                    $apple += $value;
                    unset($array_1[$key]);
                }
                if(strstr(strtolower($key) , 'facebk')){
                    $facebk += $value;
                    unset($array_1[$key]);
                }
            }
            if($google != 0.00){
                $array_1['GOOGLE']  = round($google,2);
            }
            if($jd_com != 0.00){
                $array_1['JD.COM']  = round($jd_com,2);
            }
            if($meituan != 0.00){
                $array_1['MEITUAN'] = round($meituan,2);
            }
            if($paypal != 0.00){
                $array_1['PAYPAL']  = round($paypal,2);
            }
            if($aliexpress != 0.00){
                $array_1['ALIEXPRESS.COM']  = round($aliexpress,2);
            }
            if($apple != 0.00){
                $array_1['store.apple.com']  = round($apple,2);
            }
            if($facebk != 0.00){
                $array_1['FACEBK']  = round($facebk,2);
            }

            foreach ($array_1 as $k_a => $v_a){
                $array[] = ['shop' => $k_a , 'amount' => round($v_a,2)];
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $array,
            'count' => count($array),
        ];
    }

    public function tranState($post)
    {
        $where = "state != 'DECLINED' and reason != 'Card account verification success' and type != 'foreign transaction fee' ";
        $result =[];
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            if(($end_time - $start_time - 24*60*60) > 0){
                return [
                    'code'  => 0,
                    'msg'   => lang('get info success'),
                    'data'  => $result,
                    'count' => count($result),
                ];
            }
            $where  .= " and (ctime between {$start_time} and {$end_time})";
            $list = Db::name('cards_transactions')
                ->field('tran_token,ctime,type,state')
                ->order('ctime desc')
                ->where($where)->select()
                ->toArray();

            foreach($list as $k=>$v){
                $api_json =Index::searchUserStateDiff([
                    'add_url'   => '/transactions/' . $v['tran_token'],
                    'method'    => 'GET',
                    'request_data' => ''
                ]);
                if(isset($api_json['blog']) && $api_json['blog']){
                    $response = json_decode($api_json['response'] , true);
                    $state    = $response['state'];
                    if($v['type'] == 'authorization'){
                        if($state != 'PENDING'){
                            $result[] = $v;
                        }
                    }else if($v['type'] == 'refund'){
                        if($state != 'COMPLETION'){
                            $result[] = $v;
                        }
                    }else if($v['type'] == 'authorization.clearing' ||
                        $v['type'] == 'authorization.reversal' ||
                        $v['type'] == 'authorization.reversal.issuerexpiration')
                    {
                        if($state != 'CLEARED'){
                            $result[] = $v;
                        }
                    }
                }
            }
            return [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $result,
                'count' => count($result),
            ];
        }else{
            return [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $result,
                'count' => count($result),
            ];
        }
    }

    public static function getTotalDeposit()
    {
        $list =  Index::searchOtherAdmin([
            'add_url'       => '/programreserve/transactions?count=100&start_index=0',
            'method'        => 'GET',
            'request_data'  => ''
        ]);
        $blog   = $list['blog'] ?? '';
        $count      = 0;
        $data       = [];
        $sum_amount = 0;
        if($blog){
            $response = json_decode($list['response'] , true);
            if(isset($response['data'])){
                $data_1   = [];
                foreach ($response['data'] as $v){

                        $data_1['create_time']  = str_replace(array('T','Z'),' ',$v['created_time']);
                        $data_1['type']         = $v['type'];
                        $amount = $v['amount'];
                        if($v['type'] == 'DEBIT'){
                            $amount = -$amount;
                        }
                        $data_1['amount'] = $amount;
                        $sum_amount += $amount;
                        $data[] = $data_1;
                }
            }
            $count = count($data);
        }
        return [
            'data'      => $data,
            'count'     => $count,
            'sum_amount'=> $sum_amount,
        ];
    }
}